
const Service = require('./base_service')

class FeatureServer extends Service {
  //查询列表
  index () {
    let queryString = `
      SELECT 
      id
      , feature_name as "featureName"
      , feature_uri as "featureUri"
      , comment 
      FROM sys_feature
      ORDER BY id 
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then((client) => {
          client.query(queryString, (err, res) => {
            client.release()
            if (err) {
              return reject(err)
            }
            resolve(res)
          })
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
  //新建
  create (feature) {
    let { featureName, featureUri, comment } = feature
    let queryString = `INSERT INTO 
      sys_feature(feature_name, feature_uri, comment)
      VALUES($1, $2, $3)
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(
            queryString
            , [featureName, featureUri, comment]
            , (err, res) => {
              client.release()
              if (err) return reject(err)
              resolve(res)
            }
          )
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
  update (feature) {
    let { id, featureName, featureUri, comment } = feature
    let queryString = `
      UPDATE sys_feature SET 
      feature_name = $2
      , feature_uri = $3
      , comment = $4
      WHERE id = $1
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(
            queryString
            , [id, featureName, featureUri, comment]
            , (err, res) => {
              client.release()
              if (err) return reject(err)
              resolve(res)
            }
          )
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
  delete (id) {
    let queryString = `
      DELETE FROM sys_feature WHERE id = $1
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(
            queryString
            , [id]
            , (err, res) => {
              if (err) return reject(err)
              resolve(res) 
            }
          )
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
}

module.exports = FeatureServer
